package cn.jaychang.demo5.auth.server.config;

import cn.jaychang.demo5.auth.server.exception.OAuthServerAuthenticationEntryPoint;
import cn.jaychang.demo5.auth.server.exception.OAuthServerWebResponseExceptionTranslator;
import cn.jaychang.demo5.auth.server.extension.mobile.MobilePasswordTokenGranter;
import cn.jaychang.demo5.auth.server.filter.OAuthServerClientCredentialsTokenEndpointFilter;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 认证中心配置
 * <p>
 * `@EnableAuthorizationServer` 这个注解标注这是一个认证中心
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    /**
     * Security的认证管理器，密码模式需要用到
     */
    private final AuthenticationManager authenticationManager;
    /**
     * 客户端存储策略，这里使用内存方式，后续可以存储在数据库
     */
    private final ClientDetailsService clientDetailsService;
    /**
     * 令牌存储策略
     */
    private final TokenStore tokenStore;
    /**
     * 令牌增强类，用于JWT令牌和OAuth身份进行转换
     */
    private final JwtAccessTokenConverter jwtAccessTokenConverter;
    /**
     * 用于处理客户端认证出错，包括客户端id、密码错误
     */
    private final OAuthServerAuthenticationEntryPoint authenticationEntryPoint;

    private final DataSource dataSource;

    /**
     * 令牌访问安全约束配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //自定义ClientCredentialsTokenEndpointFilter，用于处理客户端id，密码错误的异常
        OAuthServerClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = new OAuthServerClientCredentialsTokenEndpointFilter(security, authenticationEntryPoint);
        clientCredentialsTokenEndpointFilter.afterPropertiesSet();
        security.addTokenEndpointAuthenticationFilter(clientCredentialsTokenEndpointFilter);

        security
                // 开启/oauth/token_key验证端口权限访问
                .tokenKeyAccess("permitAll()")
                // 开启/oauth/token_key验证端口权限访问
                .checkTokenAccess("permitAll()")
        // 表示支持client_id和client_secret做登录认证
        // 一定不要添加allowFormAuthenticationForClients，否则自定义的OAuthServerClientCredentialsTokenEndpointFilter不生效
        // .allowFormAuthenticationForClients()
        ;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(new JdbcClientDetailsService(dataSource));

//        TODO 暂定内存模式，后续可以存储在数据库中，更加方便
//        clients.inMemory()
//                .withClient("app01")
//                .secret(passwordEncoder.encode("sec01"))
//                .resourceIds("res01")
//                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
//                .scopes("all")
//                // 是否需要授权，设置为true则不需要用户点击确认授权直接返回授权码; false则跳转到授权页面
//                .autoApprove(false)
//                // 授权码模式的回调地址
//                .redirectUris("http://www.baidu.com");
    }

    /**
     * 配置令牌访问端点
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 扩展自定义授权模式
        ArrayList<TokenGranter> tokenGranters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(tokenGranters);

        compositeTokenGranter.addTokenGranter(new MobilePasswordTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),endpoints.getOAuth2RequestFactory(), authenticationManager));

        endpoints

                // 设置异常WebResponseExceptionTranslator，用于处理用户名、密码错误，授权类型不正确的异常
                .exceptionTranslator(new OAuthServerWebResponseExceptionTranslator())
                // 授权码模式需要的authorizationCodeServices
                .authorizationCodeServices(authorizationCodeServices())
                // 密码模式需要的authenticationManager
                .authenticationManager(authenticationManager)
                // 令牌管理服务，无论哪种模式都需要
                .tokenServices(tokenServices())
                // 授权页面的url替换，如果还是想用默认的url就不用改了
                //.pathMapping("/oauth/confirm_access","自定义的url")
                //异常页面的url替换，如果还是想用默认的url就不用改了
                //.pathMapping("/oauth/error","自定义的url")
                // 自定义授权模式
                .tokenGranter(compositeTokenGranter)
                // 仅允许POST提交访问令牌， uri: /oauth/token
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
        ;
    }

    /**
     * 授权码模式的service,使用授权码模式authorization_code必须注入
     *
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }

    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        //
        tokenServices.setClientDetailsService(clientDetailsService);
        // 支持令牌的刷新
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 2);
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 3);
        tokenServices.setTokenEnhancer(jwtAccessTokenConverter);
        return tokenServices;
    }
}
